package com.hikealoha.hikealoha;

import android.annotation.TargetApi;
import android.app.Activity;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class HomeActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks{

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        // Set up the GPS pulsar.
        final LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        LocationListener mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                System.err.println("Updating GPS automatically... (G)");
                (new M2XHandlerAsync()).execute(mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
            }

            public void onStatusChanged(String provider, int i, Bundle b) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };

        LocationListener nLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                System.err.println("Updating GPS automatically... (N)");
                (new M2XHandlerAsync()).execute(mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
            }

            public void onStatusChanged(String provider, int i, Bundle b) {}
            public void onProviderEnabled(String provider) {}
            public void onProviderDisabled(String provider) {}
        };

        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, nLocationListener);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, mLocationListener);
        // End GPS block.

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, HomeFragment.newInstance())
                .commit();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        if (position == 0) {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, HomeFragment.newInstance())
                    .addToBackStack("home")
                    .commit();
        }
        else {
            fragmentManager.beginTransaction()
                    .replace(R.id.container, OptionFragment.newInstance(position))
                    .addToBackStack("option")
                    .commit();
        }
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 0:
                mTitle = getString(R.string.title_activity_home);
                break;
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
            case 5:
                mTitle = getString(R.string.title_section5);
                break;
            case 6:
                mTitle = getString(R.string.title_section6);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.home, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class HomeFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
        private ArrayList<String> categoryList;
        private ListView categoryListView;

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static HomeFragment newInstance() {
            HomeFragment fragment = new HomeFragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
            return fragment;
        }

        public HomeFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_home, container, false);
            categoryListView = (ListView) rootView.findViewById(R.id.categories_list);
            categoryList = new ArrayList<>();
            String[] listCategories = new String[]{"Everything", "Popular", "Nearby", "Beginner", "Advanced"};
            ImageView hikeImage = (ImageView) rootView.findViewById(R.id.hike_of_the_day);

            for (int i = 0; i < listCategories.length; ++i) {
                categoryList.add(listCategories[i]);
            }
            //list.addAll(Arrays.asList(listCategories));
            ListViewAdapter listViewAdapter = new ListViewAdapter (getActivity(), categoryList);
            categoryListView.setAdapter(listViewAdapter);

            categoryListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                                                        @Override
                                                        public void onItemClick(AdapterView<?> parent, final View view,
                                                                                int position, long id) {
                                                            final String item = (String) parent.getItemAtPosition(position);
                                                            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                                                            fragmentManager.beginTransaction()
                                                                    .replace(R.id.container, OptionFragment.newInstance(position))
                                                                    .addToBackStack("option")
                                                                    .commit();
                                                                    }

                                                    }
            );
            //categoryListView.
            hikeImage.setImageResource(R.drawable.sampleimage4);

            return rootView;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((HomeActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }

        public class ListViewAdapter extends BaseAdapter {
            LayoutInflater mLayoutInflater;
            List<String> mCategoryList;

            ListViewAdapter(Context context, List<String> categoryList){
                mLayoutInflater = LayoutInflater.from(context);
                this.mCategoryList = categoryList;

            }

            @Override
            public int getCount() {
                return mCategoryList.size();
            }

            @Override
            public Object getItem(int position) {

                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                //LinearLayout categoryLayout = (LinearLayout)mLayoutInflater.inflate
                //(R.layout.categories_list, parent, false);
                LayoutInflater inflater = (LayoutInflater) getActivity().getApplicationContext()
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View rowView = inflater.inflate(R.layout.categories_list, parent, false);
                TextView textView = (TextView) rowView.findViewById(R.id.list_item);
                textView.setText(mCategoryList.get(position));
                textView.setTextColor(Color.BLACK);
                textView.setTextSize(20);
                textView.setBackgroundColor(Color.WHITE);
                textView.setCompoundDrawablePadding(100);
                textView.setGravity(Gravity.CENTER_VERTICAL);
                switch (position) {
                    case 0:
                        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.listeverything, 0, 0 , 0);
                        break;
                    case 1:
                        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.popular, 0, 0 , 0);
                        break;
                    case 2:
                        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.nearby, 0, 0 , 0);
                        break;
                    case 3:
                        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.beginner, 0, 0 , 0);
                        break;
                    case 4:
                        textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.advance, 0, 0 , 0);
                        break;
                }

                return rowView;
            }
        }
    }

}
